package com.itump.base.web.action;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itump.base.util.ExcelUtil;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 标题:  <br>
 * 作者: itump<br>
 * 功能描述: 基础类<br>
 * 创建时间: 2011-07-15 15:57:25<br>
 * 版本信息: 1.0<br>
 * Copyright: Copyright (c) 2011<br>
 */
public class BaseAction extends ActionSupport{
	private static ApplicationContext ctx = null;
	
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	public String getRootPath() {
		return ServletActionContext.getServletContext().getRealPath("/");
	}
	/**
	 * Convenience method to bind objects in Actions
	 * 
	 * @param name
	 * @return
	 */
	public Object getBean(String name) {
		if (ctx == null) {
			ctx = WebApplicationContextUtils
					.getRequiredWebApplicationContext(ServletActionContext
							.getServletContext());
		}

		return ctx.getBean(name);
	}
	/**
	 * 返回指定的跳转地址
	 * @param addr
	 * @return
	 */
	public String forwardRedirect(String addr) {
		HttpServletResponse response = ServletActionContext.getResponse();
		if (response != null) {
			try {
				response.sendRedirect(addr);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 返回message页面
	 * @param message页面状态: 	close 	关闭弹出窗口，不刷新父页面;
	 *                          refresh 关闭弹出窗口，并刷新父页面
	 *                          back 	返回上一个页面
	 * @return
	 */
	public String forwardMessage(String message) {
		HttpServletResponse response = ServletActionContext.getResponse();
		if (response != null) {
			try {
				String msg="";
				if(message.equals("close")){
					msg = "<script>window.close();</script>";
				}else if(message.equals("back")){
					msg = "<script>history.back();</script>";
				}else if(message.equals("refresh")){
					msg = "<script>window.opener.location.reload();window.close();</script>";
				}
				response.getWriter().print(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 导出Excel
	 * @param excel
	 * @param response
	 * @throws IOException
	 */
	protected void writeExcel(ExcelUtil excel,HttpServletResponse response) throws IOException{
		response.reset();
		response.setContentType("application/x-msdownload;charset=GBK");
 		response.setHeader("Content-Disposition", "attachment;filename=temp.xls");
 		OutputStream os=response.getOutputStream();
 		excel.getWorkbook().write(os);
	}
	
	
	/**
	 * 分页
	 * @param total 总条目
	 * @param pageSize 每页显示多少条
	 * @param page 第几页
	 * @param pageRange 前后显示多少页
	 * @param pageParameter 在url的参数名
	 * @param request 请求
	 */
	public String pager(int total, int pageSize, int page, int pageRange, String pageParameter, HttpServletRequest request) {
		if (total < 1 || pageSize < 1 || pageParameter == null) {
			return "";
		} else {
			if (page < 1) {
				page = 1;
			}
			if (pageRange < 1) {
				pageRange = 1;
			}
			StringBuilder paraSb = new StringBuilder();
			String queryString = request.getQueryString();
			if (queryString != null) {
				String[] queries = queryString.split("&");
				for (String query : queries) {
					int idx = query.indexOf("=");
					if (idx > -1) {
						String para = query.substring(0, idx);
						if (para.length() > 0 && !pageParameter.equals(para)) {
							String value = query.substring(idx + "=".length());
							paraSb.append("&").append(para).append("=").append(value);
						}
					} else {
						paraSb.append("&").append(query).append("=");
					}
				}
			}
			String otherParas = paraSb.toString();
			int totalPages = (((total - 1) / pageSize) + 1);
			int rangeStartPage;
			int rangeEndPage;
			rangeStartPage = page - pageRange;
			if (rangeStartPage < 1) {
				rangeStartPage = 1;
			}
			rangeEndPage = rangeStartPage + pageRange + pageRange;
			if (rangeEndPage > totalPages) {
				rangeEndPage = totalPages;
				rangeStartPage = rangeEndPage - pageRange - pageRange;
			}
			if (rangeStartPage < 1) {
				rangeStartPage = 1;
			}
			
			int startItem = pageSize * (page - 1) + 1;
			int endItem = pageSize * page;
			if (endItem > total) {
				endItem = total;
			}
			
			StringBuilder pagerSb = new StringBuilder();
			pagerSb.append("<span style=\"font-family:courier;font-weight:bolder;\">");
			if (1 < rangeStartPage) {
				pagerSb.append("<a href=\"?" + pageParameter + "=1" + otherParas + "\">[1]</a>");
			}
			if (1 < rangeStartPage - 1) {
				pagerSb.append("..");
			}
			for (int ii = rangeStartPage; ii <= rangeEndPage; ii++) {
				if (ii == page) {
					pagerSb.append("[" + ii + "]");
				} else {
					pagerSb.append("<a href=\"?" + pageParameter + "=" + ii + otherParas + "\">[" + ii + "]</a>");
				}
			}
			if (totalPages > rangeEndPage + 1) {
				pagerSb.append("..");
			}
			if (totalPages > rangeEndPage) {
				pagerSb.append("<a href=\"?" + pageParameter + "=" + totalPages + otherParas + "\">[" + totalPages + "]</a>");
			}
			pagerSb.append("[" + startItem + " - " + endItem + " of " + total + "]");
			pagerSb.append("</span>");
			return pagerSb.toString();
		}
	}
	
	
	
	private static final long serialVersionUID = 8823563969472462097L;
}